package com.yinp.proapp.module.im.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.yinp.proapp.activity.bean.MyUserInfo;
import com.yinp.proapp.adapter.ComViewHolder;
import com.yinp.proapp.adapter.CommonAdapter;
import com.yinp.proapp.adapter.SingleViewHolder;
import com.yinp.proapp.base.fragment.AppBaseFragment;
import com.yinp.proapp.bean.ChangFresh;
import com.yinp.proapp.constant.SpConstants;
import com.yinp.proapp.databinding.FragmentImOneBinding;
import com.yinp.proapp.databinding.ItemConversationListBinding;
import com.yinp.proapp.module.im.activity.SingleCharActivity;
import com.yinp.proapp.module.im.bean.ConversationListBean;
import com.yinp.proapp.utils.GlideUtils;
import com.yinp.proapp.utils.SpUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.QueryListener;

/**
 * @author :yinpeng
 * date      :2021/11/23
 * package   :com.yinp.proapp.module.im.fragment
 * describe  :会话界面
 */
public class ImFragmentOne extends AppBaseFragment<FragmentImOneBinding> {
    private CommonAdapter<ConversationListBean> conversationAdapter;
    private List<ConversationListBean> conversationList = new ArrayList<>();
    private int page = 0;
    private int pageSize = 10;
    private String objectId;

    @Override
    protected void initViews(View view) {
        objectId = SpUtils.getValue(SpConstants.OBJECT_ID, "");
        getConversationList();
        initRecycler();
        EventBus.getDefault().register(this);
        refresh();
    }

    private void initRecycler() {
        conversationAdapter = new CommonAdapter<ConversationListBean>(getContext(),conversationList) {
            @Override
            protected SingleViewHolder setComViewHolder(View view, int viewType, ViewGroup parent) {
                return new SingleViewHolder(ItemConversationListBinding.inflate(mInflater, parent, false));
            }

            @Override
            public void onBindItem(SingleViewHolder holder, int position, ConversationListBean item) {
                ItemConversationListBinding binding = (ItemConversationListBinding) holder.getBinding();

                binding.tvMessage.setText(item.getLatestMessage());
                if (item.getaId().equals(objectId)) {
                    binding.tvName.setText(item.getbName());
                    GlideUtils.intoRadius(getContext(), item.getbHeadUrl(), binding.ivHead, 4);
                } else {
                    binding.tvName.setText(item.getaName());
                    GlideUtils.intoRadius(getContext(), item.getaHeadUrl(), binding.ivHead, 4);
                }
            }
        };
        conversationAdapter.setOnItemClickListener((position, view) -> {
            ConversationListBean bean = conversationList.get(position);
            //查找Person表里面id为-----的数据
            BmobQuery<MyUserInfo> bmobQuery = new BmobQuery<>();
            String targetId = bean.getaId();
            String userName = bean.getaName();
            String headUrl = bean.getaHeadUrl();
            if (targetId.equals(objectId)) {
                targetId = bean.getbId();
                userName = bean.getbName();
                headUrl = bean.getbHeadUrl();
            }
            Bundle bundle = new Bundle();
            bundle.putString("userId", targetId);
            bundle.putString("userName", userName);
            bundle.putString("headUrl", headUrl);
            bmobQuery.getObject(targetId, new QueryListener<MyUserInfo>() {
                @Override
                public void done(MyUserInfo object, BmobException e) {
                    if (e == null) {
                        goToActivity(SingleCharActivity.class, bundle);
                    } else {
                        showToast("当前账号已注销");
                    }
                }
            });
        });
        bd.rvConversationList.setLayoutManager(new LinearLayoutManager(getContext()));
        bd.rvConversationList.setHasFixedSize(true);
        bd.rvConversationList.setAdapter(conversationAdapter);
    }

    /**
     * 获取所有的会话
     */
    private void getConversationList() {
        BmobQuery<ConversationListBean> query1 = new BmobQuery<>();
        query1.addWhereEqualTo("aId", objectId);
        BmobQuery<ConversationListBean> query2 = new BmobQuery<>();
        query2.addWhereEqualTo("bId", objectId);

        List<BmobQuery<ConversationListBean>> list = new ArrayList<>();
        list.add(query1);
        list.add(query2);

        BmobQuery<ConversationListBean> query = new BmobQuery<>();
        query.or(list);
//        query.setCachePolicy(BmobQuery.CachePolicy.NETWORK_ELSE_CACHE);
        query.setLimit(pageSize);
        query.setSkip(page * pageSize);
        query.findObjects(new FindListener<ConversationListBean>() {
            @Override
            public void done(List<ConversationListBean> list, BmobException e) {
                if (e == null) {
                    if (list != null && list.size() > 0) {
                        if (page == 0) {
                            conversationList.clear();
                            conversationList.addAll(list);
                            conversationAdapter.notifyDataSetChanged();
                        } else {
                            int size = conversationList.size();
                            conversationList.addAll(list);
                            conversationAdapter.notifyItemRangeChanged(size, conversationList.size());
                        }
                    } else {
                        if (page == 0) {
                            conversationList.clear();
                            conversationAdapter.notifyDataSetChanged();
                        }
                    }
                    bd.baseRefresh.finishRefresh(true);
                    bd.baseRefresh.finishLoadMore(true);
                } else {
                    switch (e.getErrorCode()) {
                        case 101://还没有表,没有这个id的数据


                            break;
                    }
                }
            }
        });
    }

    private void refresh() {
        bd.baseRefresh.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page = 0;
                getConversationList();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page++;
                getConversationList();
            }
        });
        bd.baseRefresh.setEnableLoadMore(true);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void changeRefresh(ChangFresh changFresh) {
        if (changFresh != null && changFresh.isRefresh()) {
            page = 0;
            getConversationList();
        }
    }

    private static class ConversationViewHolder extends ComViewHolder {
        ItemConversationListBinding binding;

        public ConversationViewHolder(ItemConversationListBinding itemView) {
            super(itemView.getRoot());
            binding = itemView;
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }
}
